﻿using IRepository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repository
{
    /// <summary>
    /// 负责管理数据库连接和事务，确保多表操作的原子性
    /// </summary>
    public class UnitOfWork : IUnitOfWork,IDisposable
    {
        private readonly IDbConnection _dbConnection;
        private IDbTransaction _transaction;
        private bool _disposed = false;

        public UnitOfWork(IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
            if (_dbConnection.State != ConnectionState.Open)
            {
                _dbConnection.Open();
            }
        }

        public async Task BeginTransactionAsync()
        {
            _transaction = await Task.Run(() => _dbConnection.BeginTransaction());
        }

        public async Task CommitTransactionAsync()
        {
            await Task.Run(() => _transaction.Commit());
            _transaction.Dispose();
            _transaction = null;
        }

        public async Task RollbackTransactionAsync()
        {
            await Task.Run(() => _transaction.Rollback());
            _transaction.Dispose();
            _transaction = null;
        }

        /// <summary>
        /// 公开当前事务，供仓储层 Dapper 操作使用
        /// </summary>
        public IDbTransaction Transaction => _transaction;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _transaction?.Dispose();
                _dbConnection?.Close();
                _dbConnection?.Dispose();
            }

            _disposed = true;
        }

        ~UnitOfWork()
        {
            Dispose(false);
        }
    }
}
